<template>
    <div class="header">
        <div class="header-logo" @click="router.replace('/')">
            <el-image style="width: 144px; height: 81px" :src="url" :fit="fit" />
        </div>
        <div class="header-left">
            <p v-for="item in items" class="header-item" @click="toRouter(item.name)">
                {{ item.title }}
            </p>
        </div>

        <div class="header-right">
            <div class="empty"></div>
            <div class="circle-input">
                <!-- <el-input v-model="searchName" placeholder="搜索..." size="large">
                    <template #prefix>
                        <el-icon class="el-input__icon">
                            <search />
                        </el-icon>
                    </template>
</el-input> -->
            </div>
            <div class="avatar-down" v-if="isLogin">
                <el-dropdown trigger="hover" @command="avatarCommand">
                    <span class="el-dropdown-link">
                        <el-image class="avatar" :src="api.show + avatar" fit="fill" />
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu class="custom-dropdown-menu">
                            <div style="height: 140px;width: 100%;text-align: center;">
                                <el-image class="avatar" style="margin: 10px auto;height: 86px;width: 86px;"
                                    :src="api.show + avatar" fit="fill" />
                                <p style="height: 20px;line-height: 20px;">{{ userUtil.getUserName() }}</p>
                            </div>
                            <el-dropdown-item command="information">个人主页</el-dropdown-item>
                            <!-- <el-dropdown-item command="password">我的收藏</el-dropdown-item> -->
                            <el-dropdown-item command="like">我的点赞</el-dropdown-item>
                            <el-dropdown-item command="watch">浏览历史</el-dropdown-item>
                            <el-dropdown-item command="logOut" divided>退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <div v-else class="login-button" @click="loginShowChange">
                登录 | 注册
            </div>
        </div>
    </div>


    <el-dialog v-model="loginShow" title="登录优图，分享你的优质图片" width="400" :before-close="handleClose">
        <div class="login-box">
            <div v-if="loginType == 'code'">
                验证码登录 / 注册
                <p style="margin-bottom: 10px;"></p>
                <el-form ref="ruleFormRef" style="max-width: 360px;margin: auto" :model="account" :rules="rules"
                    label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                    <el-form-item prop="email">
                        <el-input v-model="account.email" style="width: 320px;" :prefix-icon="Message" />
                    </el-form-item><el-form-item prop="code">
                        <el-input v-model="account.code" style="width: 320px;" :prefix-icon="Lock" type="password">
                            <template #append>
                                <el-button @click="sendEmail" class="bind_code_gain" :disabled="disabled">{{ btnText
                                    }}</el-button>
                            </template></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" style="width: 100%;"
                            @click="registerOrLogin(ruleFormRef)">登录/注册</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-else>
                密码登录
                <p style="margin-bottom: 10px;"></p>
                <el-form ref="ruleFormRef" style="max-width: 360px;margin: auto" :model="account" :rules="rules"
                    label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                    <el-form-item prop="email">
                        <el-input v-model="account.email" style="width: 320px;" :prefix-icon="Message" />
                    </el-form-item><el-form-item prop="password">
                        <el-input v-model="account.password" style="width: 320px;" :prefix-icon="Lock"
                            type="password" />
                    </el-form-item>
                    <el-form-item>
                        <div style="display: flex;justify-content: space-between;width: 100%">
                            <el-button type="primary" style="width: 45%;" plain @click="loginType = 'code'"
                                color="#79bbff">注册</el-button>
                            <el-button type="primary" style="width: 45%;" @click="loginByPassword">登录</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <p v-if="loginType == 'code'" class="typeChange" @click="loginType = 'password'">密码登录</p>
            <p v-else class="typeChange" @click="loginType = 'code'">验证码登录</p>
        </div>
    </el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import url from "@/assets/logo.png"
import user from "@/utils/userUtil"
import api from '@/utils/userApi'
import { Message, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import userUtil from '@/utils/userUtil'
import { useRouter } from 'vue-router'
const router = useRouter()
const avatar = ref(userUtil.getAvatar())
const userName = ref(userUtil.getUserName())
const isLogin = ref(user.getToken() != null ? true : false)
const loginShow = ref(false)
const loginType = ref("code")
const account = ref({
    email: '',
    password: '',
    code: ''
})
const disabled = ref(false)
const btnText = ref("发送验证码")
const loginShowChange = () => {
    account.value = {
        email: '',
        password: '',
        code: ''
    }
    loginShow.value = true
}
const ruleFormRef = reactive({})
const rules = reactive({
    email: [
        { required: true, message: '邮箱不能为空!', trigger: 'blur' },
        { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱!', trigger: 'blur' }
    ], password: [
        { required: true, message: '密码不能为空!', trigger: 'blur' },

    ], code: [
        { required: true, message: '验证码不能为空!', trigger: 'blur' },

    ],

})

const loginByPassword = () => {
    api.loginByEmailAndPassword(account.value).then(res => {
        var t = 'error'
        if (res.success) {
            t = 'success'
            userUtil.setToken(res.token)
            loginShow.value = false
            isLogin.value = true
            api.getMyself().then(a => {
                if (a.success) {
                    avatar.value = a.data.avatar
                    userUtil.setUser(a.data)
                }
            })
        }
        ElMessage({ type: t, message: res.message })
    })
}

const registerOrLogin = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.chechEmail(account.value.email).then(x => {
                if (x.success) {
                    api.registerByEmailAndCode(account.value).then(res => {
                        if (res.success) {
                            userUtil.setToken(res.token)
                            loginShow.value = false
                            isLogin.value = true
                            api.getMyself().then(a => {
                                if (a.success) {
                                    avatar.value = a.data.avatar
                                    userUtil.setUser(a.data)
                                }
                            })
                            ElMessage({
                                type: 'success',
                                message: res.message
                            })
                        }
                    })
                } else {
                    api.loginByEmailAndCode(account.value).then(res => {
                        if (res.success) {
                            userUtil.setToken(res.token)
                            loginShow.value = false
                            isLogin.value = true
                            api.getMyself().then(a => {
                                if (a.success) {
                                    avatar.value = a.data.avatar
                                    userUtil.setUser(a.data)
                                }
                            })
                            ElMessage({
                                type: 'success',
                                message: res.message
                            })
                        }
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const sendEmail = () => {
    const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (account.value.email.match(pattern) != null) {
        api.sendEmail(account.value.email).then(res => {
            if (res.success) {
                ElMessage({
                    type: 'success',
                    message: res.message
                })
                btnText.value = '请稍候...'
                startCountDown(60)
            } else {
                ElMessage({
                    type: 'error',
                    message: res.message
                })
            }
        })
    }

}

const startCountDown = (seconds) => {
    seconds = seconds ? seconds : 60;
    btnText.value = seconds + "s后获取";
    let countdown = setInterval(() => {
        if (seconds > 0) {
            btnText.value = seconds + "s后获取";
            --seconds;
        } else {
            btnText.value = "获取验证码";
            disabled.value = false;
            clearInterval(countdown);
        }
    }, 1000);
}



//header
// const searchName = ref('')
const avatarCommand = (command) => {
    switch (command) {
        case 'logOut': {
            userUtil.logout()
            isLogin.value = false
            ElMessage({
                // type: 'success',
                message: '退出登录成功!'
            })
        } case 'information': {
            router.push({ name: 'userPhoto', params: { id: userUtil.getuserId() } })
            return
        } case 'like': {
            router.push({ name: 'like', params: { id: userUtil.getuserId() } })
            return

        } case 'watch': {
            router.push({ name: 'watch', params: { id: userUtil.getuserId() } })
            return

        }
    }
}

const items = ref([
    {
        title: '首页',
        name: '/'
    },
    {
        title: '热门榜单',
        name: 'test'
    }
])

const toRouter = (name) => {
    router.push(name)
}


</script>




<style>
.typeChange:hover {
    cursor: pointer;
}

.typeChange {
    width: 100px
}

.login-box {
    height: 180px;
    padding: 22px;
    border-top: #f1f2f5 1px solid
}

.login-button:hover {
    cursor: pointer;
}

.login-button {
    background: rgba(30, 128, 255, .05);
    border: 1px solid rgba(30, 128, 255, .3);
    border-radius: 4px;
    margin-top: 31px;
    padding: 10px;
    color: #007fff;
    line-height: 16px;
    font-size: 14px;
    /* font-weight: 400; */
    height: 16px;
    /* overflow: hidden; */
    /* display: flex; */
    align-items: center;
}

.header {
    height: 100px;
    padding: 0 40px;
    display: flex;
    justify-content: space-between;
    line-height: 100px;
    /* margin-bottom: 5px; */

    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.header-left {
    width: 40%;
    display: flex;
    justify-content: left;
}

.header-left .header-item {
    /* background-color: red; */
    width: 80px;
    text-align: center;
}

.header-left .header-item:hover {
    cursor: pointer;
    color: #999;
}



.header .header-logo {
    padding-top: 10px;
}

.header .header-right {
    width: 40%;
    display: flex;
}

.header .header-logo:hover {
    cursor: pointer;
}

.empty {
    width: 40%
}

.circle-input {
    display: inline-block;
    border-radius: 50px;
    /* overflow: hidden; */
    width: 240px;
    height: 40px;
}

.circle-input .el-input__wrapper {
    /* box-shadow: none; */
    border-radius: 50px;
}

.avatar-down {
    width: 40%;
    padding-left: 30px
}

.avatar {
    width: 46px;
    height: 46px;
    margin-top: 27px;
    border-radius: 50%;
}

.avatar:hover {
    cursor: pointer;
}

.custom-dropdown-menu {
    width: 220px;
    /* 设置自定义宽度 */
}

.custom-dropdown-menu .el-dropdown-menu__item {
    height: 25px;
    /* padding-left: 70px; */
    text-align: center;
    /* 将文本居中 */
}
</style>